<template>
  <div class="person">
    <!-- v-model:用于在表单输入和应用状态之间创建双向数据绑定 -->
    姓: <input type="text" v-model="firstName" /> <br />
    名: <input type="text" v-model="lastName" /> <br />
    <button @click="changeFullName">将全名改为li-si</button>
    全名: <span>{{ fullName }}</span> <br />
    全名: <span>{{ fullName }}</span> <br />
    全名: <span>{{ fullName }}</span> <br />
    全名: <span>{{ fullName2() }}</span> <br />
    全名: <span>{{ fullName2() }}</span> <br />
    全名: <span>{{ fullName2() }}</span> <br />
  </div>
</template>

<script lang="ts" setup name="Person">
  import { ref, computed } from "vue";

  let firstName = ref("zhang");
  let lastName = ref("xuyuan");

  function changeFullName() {
    fullName.value = "li-si";
  }

  //这么定义的一个fullName是一个计算属性,且是只读的
  // let fullName = computed(() => {
  //   console.log(2);
  //   return (
  //     firstName.value.slice(0, 1).toUpperCase() +
  //     firstName.value.slice(1) +
  //     "-" +
  //     lastName.value
  //   );
  // });

  //这么定义的一个fullName是一个计算属性,是可读可写的
  let fullName = computed({
    get() {
      return (
        firstName.value.slice(0, 1).toUpperCase() +
        firstName.value.slice(1) +
        "-" +
        lastName.value
      );
    },
    set(val) {
      const [str1, str2] = val.split("-");
      firstName.value = str1;
      lastName.value = str2;
    },
  });

  //方法读取数据没有缓存
  function fullName2() {
    console.log(1);
    return (
      firstName.value.slice(0, 1).toUpperCase() +
      firstName.value.slice(1) +
      "-" +
      lastName.value
    );
  }
</script>

<style scoped>
  .person {
    background-color: aqua;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
  }

  button {
    margin-left: 5px;
    margin-right: 5px;
  }
</style>
